package com.system.borrow.fragment;

import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.system.borrow.Constant.URLDefind;
import com.system.borrow.R;
import com.system.borrow.activity.ActionActivity;
import com.system.borrow.activity.CreditActivity;
import com.system.borrow.activity.DetailActivity;
import com.system.borrow.activity.LoanActivity;
import com.system.borrow.activity.LoginActivity;
import com.system.borrow.activity.WebViewActivity;
import com.system.borrow.adapter.HotAdapter;
import com.system.borrow.adapter.TuiJianAdapter;
import com.system.borrow.bean.BannerList;
import com.system.borrow.bean.GloData;
import com.system.borrow.bean.TuiJian;
import com.system.borrow.cache.CacheMode;
import com.system.borrow.callback.DialogCallback;
import com.system.borrow.http.model.HttpParams;
import com.system.borrow.http.utils.OkHttpUtils;
import com.system.borrow.utils.GlideImageLoader;
import com.system.borrow.utils.ListViewUtils;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.Transformer;
import com.youth.banner.listener.OnBannerClickListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Request;
import okhttp3.Response;

/**
 * ================================================
 * 作    者：LuCenly(落尘)
 * 版    本：1.0
 * 创建日期：2016/11/17 23:34
 * 描    述：TODO
 * ================================================
 */
public class HomeFragment extends Fragment implements View.OnClickListener{
    List<String> images = new ArrayList<>();
    View myView;
    Banner banner;
    ListView lv_tuijian,lv_hot;
    TuiJianAdapter tuijianAdapter;
    HotAdapter hotAdapter;
    LinearLayout ll_loan,ll_action,ll_xyk,ll_change;
    ScrollView sv;
    int categoryId=0;
    List<BannerList> banners = new ArrayList<>();
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (myView == null) {
            myView = inflater.inflate(R.layout.fragment_home, container, false);
        } else {
            ViewParent parent = myView.getParent();
            if (parent instanceof ViewGroup) {
                ((ViewGroup) parent).removeView(myView);
            }
        }
        init(myView);
        loadBanner();
        addAction();
        initListener();
        loadData();
        loadXyk();
        return myView;
    }

    private void loadXyk() {
        OkHttpUtils.get(URLDefind.HOME_XYK)
                .tag(this)
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new DialogCallback<String>(getActivity(),String.class,null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    JSONArray data = json.getJSONArray("data");
                                    JSONObject jsonObject = (JSONObject) data.get(0);
                                    JSONArray dataList = jsonObject.getJSONArray("dataList");
                                    Gson gson = new Gson();
                                    TypeToken<List<TuiJian>> token = new TypeToken<List<TuiJian>>(){};
                                    List<TuiJian> tuiJianList = gson.fromJson(dataList.toString(),token.getType());
                                    hotAdapter.setList(tuiJianList);
                                    ListViewUtils.setListViewHeightBasedOnChildren(lv_hot);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    JSONArray data = json.getJSONArray("data");
                                    JSONObject jsonObject = (JSONObject) data.get(0);
                                    JSONArray dataList = jsonObject.getJSONArray("dataList");
                                    Gson gson = new Gson();
                                    TypeToken<List<TuiJian>> token = new TypeToken<List<TuiJian>>(){};
                                    List<TuiJian> tuiJianList = gson.fromJson(dataList.toString(),token.getType());
                                    hotAdapter.setList(tuiJianList);
                                    ListViewUtils.setListViewHeightBasedOnChildren(lv_hot);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    /**
     * 数据列表
     */
    private void loadData() {
        OkHttpUtils.get(URLDefind.HOME_LOAN)
                .tag(this)
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new DialogCallback<String>(getActivity(),String.class,null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    JSONArray data = json.getJSONArray("data");
                                    JSONObject jsonObject = (JSONObject) data.get(0);
                                    categoryId = jsonObject.getInt("id");
                                    JSONArray dataList = jsonObject.getJSONArray("dataList");
                                    Gson gson = new Gson();
                                    TypeToken<List<TuiJian>> token = new TypeToken<List<TuiJian>>(){};
                                    List<TuiJian> tuiJianList = gson.fromJson(dataList.toString(),token.getType());
                                    tuijianAdapter.setList(tuiJianList);
                                    ListViewUtils.setListViewHeightBasedOnChildren(lv_tuijian);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    JSONArray data = json.getJSONArray("data");
                                    JSONObject jsonObject = (JSONObject) data.get(0);
                                    JSONArray dataList = jsonObject.getJSONArray("dataList");
                                    Gson gson = new Gson();
                                    TypeToken<List<TuiJian>> token = new TypeToken<List<TuiJian>>(){};
                                    List<TuiJian> tuiJianList = gson.fromJson(dataList.toString(),token.getType());
                                    tuijianAdapter.setList(tuiJianList);
                                    ListViewUtils.setListViewHeightBasedOnChildren(lv_tuijian);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                });
    }

    private void loadBanner() {
        OkHttpUtils.get(URLDefind.BANNER)
                .tag(this)
                .cacheMode(CacheMode.FIRST_CACHE_THEN_REQUEST)
                .execute(new DialogCallback<String>(getActivity(),String.class,null) {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    Gson gson = new Gson();
                                    TypeToken<List<BannerList>> token = new TypeToken<List<BannerList>>(){};
                                    List<BannerList> list = gson.fromJson(json.getJSONArray("data").toString(),token.getType());
                                    setBanner(list);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                            if(s!=null){
                                try {
                                    JSONObject json = new JSONObject(s);
                                    int statusCode = json.getInt("statusCode");
                                    if(statusCode==200){
                                        Gson gson = new Gson();
                                        TypeToken<List<BannerList>> token = new TypeToken<List<BannerList>>(){};
                                        List<BannerList> list = gson.fromJson(json.getJSONArray("data").toString(),token.getType());
                                        setBanner(list);
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }
                    }
                });
    }

    private void initListener() {
        banner.setFocusable(true);
        banner.setFocusableInTouchMode(true);
        banner.requestFocus();
        ll_loan.setOnClickListener(this);
        ll_action.setOnClickListener(this);
        ll_xyk.setOnClickListener(this);
        ll_change.setOnClickListener(this);
        sv.smoothScrollTo(0,0);
        lv_tuijian.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    if(GloData.getCustomerDTO()==null){
                        Intent loginIntent = new Intent(getActivity(),LoginActivity.class);
                        startActivity(loginIntent);
                        return;
                    }
                    Intent intent = new Intent(getActivity(), DetailActivity.class);
                    TuiJian tuiJian = (TuiJian) tuijianAdapter.getItem(position);
                    intent.putExtra("id",tuiJian.id);
                    startActivity(intent);
                }
        });
        lv_hot.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if(GloData.getCustomerDTO()==null){
                    Intent loginIntent = new Intent(getActivity(),LoginActivity.class);
                    startActivity(loginIntent);
                    return;
                }
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                TuiJian tuiJian = (TuiJian) hotAdapter.getItem(position);
                intent.putExtra("name",tuiJian.name);
                intent.putExtra("url",tuiJian.url);
                intent.putExtra("id",tuiJian.id);
                intent.putExtra("type",1);
                startActivity(intent);
            }
        });
        banner.setOnBannerClickListener(new OnBannerClickListener() {
            @Override
            public void OnBannerClick(int position) {
                if(GloData.getCustomerDTO()==null){
                    Intent loginIntent = new Intent(getActivity(),LoginActivity.class);
                    startActivity(loginIntent);
                    return;
                }
                Log.v("position",position+"==================");
                BannerList bannerList = banners.get(position-1);
                Intent intent = new Intent(getActivity(), WebViewActivity.class);
                intent.putExtra("name","活动");
                intent.putExtra("url",bannerList.url);
                intent.putExtra("id",bannerList.dataId);
                startActivity(intent);
            }
        });
    }
    private void addAction() {
        tuijianAdapter = new TuiJianAdapter(getActivity());
        lv_tuijian.setAdapter(tuijianAdapter);
        hotAdapter = new HotAdapter(getActivity());
        lv_hot.setAdapter(hotAdapter);
    }

    private void init(View myView) {
        banner = (Banner) myView.findViewById(R.id.banner);
        lv_tuijian = (ListView) myView.findViewById(R.id.lv_tuijian);
        lv_hot = (ListView) myView.findViewById(R.id.lv_hot);
        ll_loan = (LinearLayout) myView.findViewById(R.id.ll_loan);
        ll_action = (LinearLayout) myView.findViewById(R.id.ll_action);
        ll_xyk = (LinearLayout) myView.findViewById(R.id.ll_xyk);
        sv = (ScrollView) myView.findViewById(R.id.sv);
        ll_change = (LinearLayout) myView.findViewById(R.id.ll_change);
    }

    private void setBanner(List<BannerList> list) {
        this.banners = list;
        //设置banner样式
        banner.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        //设置图片加载器
        banner.setImageLoader(new GlideImageLoader());
       images = new ArrayList<>();
        for (BannerList banner:
             list) {
            images.add(banner.img);
        }
        //设置图片集合
        banner.setImages(images);
        //设置banner动画效果
//        banner.setBannerAnimation(Transformer.DepthPage);
        banner.setBannerAnimation(Transformer.Default);
//        banner.setBannerAnimation(Transformer.ZoomOutSlide);
        //设置标题集合（当banner样式有显示title时）
//        banner.setBannerTitles(Arrays.asList(titles));
        //设置自动轮播，默认为true
        banner.isAutoPlay(true);
        //设置轮播时间
        banner.setDelayTime(3000);
        //设置指示器位置（当banner模式中有指示器时）
        banner.setIndicatorGravity(BannerConfig.CENTER);
        //banner设置方法全部调用完毕时最后调用
        banner.start();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_loan:
                Intent loan_intent = new Intent(getActivity(), LoanActivity.class);
                startActivity(loan_intent);
            break;
            case R.id.ll_action:
                Intent action_intent = new Intent(getActivity(), ActionActivity.class);
                startActivity(action_intent);
                break;
            case R.id.ll_xyk:
                Intent xyk_intent = new Intent(getActivity(), CreditActivity.class);
                startActivity(xyk_intent);
                break;
            case R.id.ll_change:
                change();
                break;
        }
    }

    private void change() {
        if(categoryId==0){
            return;
        }
        HttpParams params = new HttpParams();
        OkHttpUtils.get(URLDefind.HOME_CHANGE)
                .tag(this)
                .cacheMode(CacheMode.NO_CACHE)
                .params("categoryId",categoryId+"")
                .execute(new DialogCallback<String>(getActivity(),String.class,"加载中...") {
                    @Override
                    public void onResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                        if(s!=null){
                            try {
                                JSONObject json = new JSONObject(s);
                                int statusCode = json.getInt("statusCode");
                                if(statusCode==200){
                                    JSONArray data = json.getJSONArray("data");
                                    Gson gson = new Gson();
                                    TypeToken<List<TuiJian>> token = new TypeToken<List<TuiJian>>(){};
                                    List<TuiJian> tuiJianList = gson.fromJson(data.toString(),token.getType());
                                    tuijianAdapter.setList(tuiJianList);
                                    ListViewUtils.setListViewHeightBasedOnChildren(lv_tuijian);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                    }

                    @Override
                    public void onCacheResponse(boolean isFromCache, String s, Request request, @Nullable Response response) {
                    }
                });
    }
}
